﻿using System;
using System.Net;
using Castle.MicroKernel.ComponentActivator;
using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.Context;

namespace Structura.Castle.Windsor.Lifecycle
{
   

#if (!SILVERLIGHT)
	[Serializable]
#endif
	public class SingletonComponentActivator : DefaultComponentActivator
	{
		public SingletonComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction) : base(model, kernel, onCreation, onDestruction)
		{
		}

		#region implementation 1

		public virtual object Create(CreationContext context)
		{
			object instance = InternalCreate(context);

			// onCreation(model, instance);

			return instance;
		}

		protected override object InternalCreate(CreationContext context)
		{
			object instance = Instantiate(context);

			// SetUpProperties(instance, context);

			ApplyCommissionConcerns(instance);

			return instance;
		}

		internal void SetUpProperties(object instance, CreationContext context)
		{
			base.SetUpProperties(instance, context);

			// called when the object got fully constructed
			OnCreation(Model, instance);
		}

		#endregion

		#region implementation 2

		public object Create(CreationContext context, ref object instance)
		{
			InternalCreate(context, ref instance);

			OnCreation(Model, instance);

			return instance;
		}

		protected object InternalCreate(CreationContext context, ref object instance)
		{
			instance = Instantiate(context);

			SetUpProperties(instance, context);

			ApplyCommissionConcerns(instance);

			return instance;
		}

		#endregion
	}
}
